package com.blazhovsky.mk.androidlan;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity
{
	String klientIP = "";

	Button btnPrati;
	EditText porakaZaPrakjanje;
	EditText adresaZaPrakjanje;
	TextView primenaPoraka;
	ListView adresiZaPrakjanje;
	ArrayList<String> adresi = new ArrayList<String>();

	Server s;
	NitkaZaPrakjanje prati;
	NitkaZaSkeniranje skeniraj;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		adresiZaPrakjanje = (ListView) findViewById(R.id.lvAdresi);

		primenaPoraka = (TextView) findViewById(R.id.dobienaPoraka);
		primenaPoraka.setMovementMethod(new ScrollingMovementMethod());
		primenaPoraka.setText("");

		adresaZaPrakjanje = (EditText) findViewById(R.id.adresaZaPrakjanje);
		porakaZaPrakjanje = (EditText) findViewById(R.id.porakaZaPrakjanje);

		btnPrati = (Button) findViewById(R.id.btnKlient);		

		s = new Server(this);
		s.pocni();		

		skeniraj = new NitkaZaSkeniranje(this);
		skeniraj.pocni();

		adresiZaPrakjanje.setOnItemClickListener(new OnItemClickListener()
		{

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				// TODO Auto-generated method stub
				klientIP = adresiZaPrakjanje.getItemAtPosition(arg2).toString();
				adresaZaPrakjanje.setText(klientIP);
				System.out.println(klientIP);
			}

		});

		btnPrati.setOnClickListener(new OnClickListener()
		{

			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				prati = new NitkaZaPrakjanje(MainActivity.this, porakaZaPrakjanje.getText().toString());
				prati.pocni();
			}
		});
	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();
		s.server = true;
		s.pocni();
		skeniraj.pocni();
	}

	@Override
	protected void onPause()
	{
		// TODO Auto-generated method stub
		super.onPause();
		s.server = false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void refresh(String dobienaPoraka)
	{
		System.out.println("refresh!");
		primenaPoraka.setText(primenaPoraka.getText() + dobienaPoraka);
	}
}
